// pages/addNewinvoice/addNewinvoice.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from "../../miniprogram_npm/@vant/weapp/dialog/dialog";

import api from '../../utils/api';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // invFormContentList: '', //开票内容列表
    coId: '',
    cusId: '',
    unitId: '',
    code: '',
    userName: '',
    deptName: '',
    deptId: '',
    showType: false,
    showType2: false,
    showType_yewu: false,
    columns: [], //下拉选
    columns2: [], //下拉选
    columns_yewu: [],
    typeValue: '', //发票类型
    moneyValue: '',
    taxesValue: '', //税款
    // status: '',
    radio: '0', //是否到款
    receTermCode: '', //到款项code

    receiveType: '', //到款类型
    // label: 0,
    radio2: '1', //是否关联合同
    is_cpyjf: '0', // 产品已交付
    remarks: '', //备注
    date: '',
    show: false,
    text: '',
    keyId: '', //税率
    dictKey: '', //发票类型
    dictKey2: '', //到款类型
    businessTypeStr: '', //业务类型
    businessType: '',
    getTime: '', //转时间戳之后
    invid: '', //新建发票id
    uuid: '',
    saveButton: '',

    clicknext: false, //点击下一步
    invFormContentList: '', //开票内容列表
    sysDictContractList: '', //合同列表
    invFormTaskList: '', //合同任务号列表
    sysDictCustomerList: '', //往来单位
    cusId: '', //客户id 
    sysDictCustomer: '',
    minDate: '',
    currDate: '',
    maxDate: '',
    todayDate: '',
    zanwuwldw: true,
    invtaxRate: '', //该发票税率

    fileList: [],

    kaipiaoneirong: true, //开票内容显示与否

    offlineYearClaimed: '', // 是否显示该字段 线下或往年已认领
    isOfflineYearClaimed: '0', //该字段默认显示为否
  },

  //业务类型 弹框
  businessType(event) {
    // console.log(event,"业务类型")
    this.setData({
      showType_yewu: true
    });
    this.businessTypeList()

  },
  //业务类型列表初始渲染
  businessTypeList() {
    let that = this;
    api.getBusinessTypeList({
      data: {
        coId: that.data.coId,
      },
      success: function (res) {
        // console.log(res.data.data, "业务类型")
        if (res.data.code = 200) {
          that.data.columns_yewu = [];
          if (res.data.data.length > 0) {
            res.data.data.forEach((item) => {
              let obj = {
                text: item.dictValue,
                businessType: item.dictKey,
                // dictValue02: item.dictValue02,
              }
              that.data.columns_yewu.push(obj)
              // console.log(that.data.columns_yewu, 'oooo')
            });
            that.setData({
              columns_yewu: that.data.columns_yewu,
              showType_yewu: true
            })
          } else {
            that.setData({
              showType_yewu: false
            })
          }

        }
      }
    })
  },
  onCancelType_yw() {
    this.setData({
      showType_yewu: false
    });
  },
  onConfirmType_yw(e) {
    const {
      value,
    } = e.detail;
    // console.log(value, "val")
    let text = value.text;
    this.data.businessType = value.businessType;
    this.setData({
      businessTypeStr: value.text,
      businessType: this.data.businessType,
      showType_yewu: false,
    })
    // console.log(this.data.businessType)
  },

  //发票类型 弹框
  focus(e) {
    // console.log(e.detail.value, "focus")
    this.setData({
      showType: true,
      typeValue: e.detail.value
    });
    if (e.detail.value == '') {
      this.showList()
    }
  },
  change(e) {
    // console.log(e.detail, "change")
    this.setData({
      showType: true,
      typeValue: e.detail
    });
    this.showList()
  },
  click(e) {
    this.showList()
  },
  //发票类型列表初始渲染
  showList() {
    let that = this;
    api.addNewinvType({
      data: {
        coId: this.data.coId,
        word: this.data.typeValue,
      },
      success: function (res) {
        // console.log(res.data.data, "addNewinvType  发票类型")
        if (res.data.code = 200) {
          that.data.columns = [];
          if (res.data.data.length > 0) {
            res.data.data.forEach((item) => {
              let obj = {
                text: item.dictValue,
                keyId: item.dictValue02,
                dictKey: item.dictKey
              }
              that.data.columns.push(obj)
              // console.log(that.data.columns, 'oooo')
            });
            that.setData({
              columns: that.data.columns,
            })
            that.setData({
              showType: true
            })
          } else {
            that.setData({
              showType: false
            })
          }

        }
      }
    })
  },
  onCancelType() {
    this.setData({
      showType: false
    });
  },
  onConfirmType(e) {
    const {
      value,
    } = e.detail;
    // console.log(value, "val")
    //发票类型 选择收据的时候 开票内容不显示
    // if(value.dictKey == 8){
    //   console.log('选择 收据--开票内容不显示')
    //   this.setData({
    //     kaipiaoneirong:false,
    //   })
    // }else{
    //   this.setData({
    //     kaipiaoneirong:true,
    //   })
    // }

    let keyId = value.keyId
    let text = value.text;
    let dictKey = value.dictKey
    this.data.keyId = keyId;
    this.data.dictKey = dictKey;
    this.setData({
      typeValue: value.text,
      showType: false,
    })
  },
  //输入开票金额自动计算税款
  onfieldChange(e) {
    if (this.data.typeValue != '') {
      this.setData({
        moneyValue: e.detail,
        // moneyValue: e.detail.toString().replace(/(?!^)(?=(\d{3})+\.)/g, ","),
        taxesValue: (e.detail * this.data.keyId).toFixed(2)
      })
    } else {
      wx.showToast({
        title: '请先选择发票类型',
        icon: 'none'
      })
    }
  },
  //到款类型 弹框
  onradioTypefocus(e) {
    this.setData({
      showType2: true,
      receiveType: e.detail.value
    });
    this.showListType()
    // if (e.detail.value == '') {
    //   this.showListType()
    // }
  },
  onradioTypechange(event) {
    this.setData({
      showType2: true,
      receiveType: event.detail
    })
    this.showListType()
  },
  onradioTypeclick(e) {
    // console.log(e)
    this.showListType()
  },

  //4.27新增 线下或往年已认领 单选框
  onoffChange(event) {
    const that = this;
    this.setData({
      isOfflineYearClaimed: event.detail,
    })
    // console.log(event.detail)
    //是 1 到款项不显示 到款日期默认(2022.1.1) 到款类型默认（线下或往年已认领 receiveType=7） 
    if (event.detail == 1) {
      this.setData({
        date: that.formatDate(new Date(`${new Date().getFullYear()-1}/12/31`)),
        receiveType: '线下或往年已认领',
        dictKey2: "7", //到款类型默认为 线下或往年已认领
      })
    } else {
      this.setData({
        date: that.formatDate(new Date()),
        // receiveType:'',
        // dictKey2:'',//到款类型默认为 线下或往年已认领
      })
    }
  },

  //到款类型列表初始渲染
  showListType() {
    let that = this;
    api.getBankTypeList({
      data: {
        coId: this.data.coId,
        // word: this.data.receiveType,
      },
      success: function (res) {
        // console.log(res.data.data, "getBankTypeList到款类型列表")
        if (res.data.code == 200) {
          if (res.data.data.length > 0) {
            res.data.data.forEach((item) => {
              let obj = {
                text: item.dictValue,
                dictKey2: item.dictKey
              }
              that.data.columns2.push(obj)
              // console.log(that.data.columns2, 'oooo')
            });
            that.setData({
              columns2: that.data.columns2,
            })
            that.setData({
              showType2: true
            })
          } else {
            that.setData({
              showType2: false
            })
          }
        }
      }
    })
  },
  onCancelType2() {
    this.setData({
      showType2: false
    });
  },
  onConfirmType2(e) {
    const {
      value,
    } = e.detail;
    // console.log(value, "val")
    let text = value.text;
    let dictKey2 = value.dictKey2
    this.data.dictKey2 = dictKey2;
    this.setData({
      receiveType: value.text,
      showType2: false,
    })
  },
  //单选框改变 是否到款
  onradioChange(event) {
    const that = this;
    this.setData({
      radio: event.detail,
    });
    if (event.detail == 1) {
      //是到款
      this.setData({
        offlineYearClaimed: 1,
      })
    }
    if (event.detail == 0) {
      wx.removeStorageSync('receTermCode')
      wx.removeStorageSync('receTermDate')
      wx.removeStorageSync('receTerm2');
      wx.removeStorageSync('receTerm');
      wx.removeStorageSync('dkClaimId');
      wx.removeStorageSync('receiveId');

      wx.removeStorageSync('bankType')
      wx.removeStorageSync('bankTypeStr')
      wx.removeStorageSync('date')

      this.data.receiveId = ''
      this.data.dkClaimId = ''
      // this.data.bankType=''
      this.setData({
        receiveType: '',
        date: that.formatDate(new Date()),
        // offlineYearClaimed:'',
        // isOfflineYearClaimed:''
      })

      this.setData({
        receTermCode: ''
      });

    }
    //原保存 接口 但不弹窗提示
    this.setData({
      sysDictCustomer: this.data.sysDictCustomer
    })
    // console.log(this.data.sysDictCustomer)
    if (!this.data.sysDictCustomer) {
      this.data.sysDictCustomer = []
    }
    api.invEdit({
      method: 'post',
      data: {
        id: this.data.invid,
        updateBy: this.data.unitId,
        fpType: this.data.dictKey,
        taxRate: this.data.keyId,
        // money: this.data.moneyValue.toString().replace(/(?!^)(?=(\d{3})+\.)/g, ","),
        money: this.data.moneyValue.toString(),
        cusId: this.data.cusId,
        isReceived: this.data.radio,
        //到款项id
        receiveId: this.data.receiveId,
        dkClaimId: this.data.dkClaimId,
        receiveDate: this.data.getTime,
        sysDictCustomer: this.data.sysDictCustomer,
        needContract: parseInt(this.data.radio2),
        businessType: this.data.businessType,
        remarks: this.data.remarks,
        isOfflineClaimed: this.data.isOfflineYearClaimed, // 线下或往年已认领 是否

      },
      success: function (res) {
        // console.log(res.data.data, "invEdit")
        if (res.data.code == 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          })
        } else {
          // console.log('保存成功，但是不需要弹窗111111')
        }
      }
    })
  },
  handlecpyjf(event) {
    // console.log(event.detail, "产品已交付")
    this.setData({
      is_cpyjf: event.detail
    })
  },
  //单选框改变2 是否关联合同
  onradio2Change(event) {
    // console.log(event.detail, "是否关联合同")
    //否关联合同的时候显示无合同原因
    if (event.detail == 0) {
      this.setData({
        ContractReason: true
      })
    }
    this.setData({
      radio2: event.detail,
      noContractReason: '',
    });
    //  this.save()
    //原保存 接口 但不弹窗提示
    this.setData({
      sysDictCustomer: this.data.sysDictCustomer
    })
    // console.log(this.data.sysDictCustomer)
    if (!this.data.sysDictCustomer) {
      this.data.sysDictCustomer = []
    }
    api.invEdit({
      method: 'post',
      data: {
        id: this.data.invid,
        updateBy: this.data.unitId,
        fpType: this.data.dictKey,
        taxRate: this.data.keyId,
        // money: this.data.moneyValue.toString().replace(/(?!^)(?=(\d{3})+\.)/g, ","),
        money: this.data.moneyValue.toString(),
        cusId: this.data.cusId,
        isReceived: this.data.radio,
        //到款项id
        receiveId: this.data.receiveId,
        dkClaimId: this.data.dkClaimId,
        receiveDate: this.data.getTime,
        sysDictCustomer: this.data.sysDictCustomer,
        needContract: parseInt(this.data.radio2),
        businessType: this.data.businessType,
        remarks: this.data.remarks,
        noContractReason: this.data.noContractReason //无合同原因
      },
      success: function (res) {
        // console.log(res.data.data, "invEdit")
        if (res.data.code == 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          })
        } else {
          // console.log('保存成功，但是不需要弹窗')
        }
      }
    })
  },
  //选择到款项 点击跳转”选择到款“页面
  onreceTermChange() {
    wx.navigateTo({
      url: '/pages/selectReceived/selectReceived?money=' + this.data.moneyValue + '&from=' + 1,
    })
  },
  //日期弹框
  onDisplay() {
    // console.log(this.formatDate(new Date()), '日期弹框')
    this.setData({
      show: true,
      date: this.formatDate(new Date(this.data.date)),
      currDate: new Date(this.data.date).getTime(),
      minDate: new Date(2018, 0, 1).getTime(),
      maxDate: new Date(new Date().getFullYear() + 2, new Date().getMonth() + 1).getTime(),
    });
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  formatDate(date) {
    //转时间戳
    this.setData({
      getTime: date.getTime()
    })
    // console.log(this.data.getTime)
    date = new Date(date);
    return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
  },
  onConfirm(event) {
    // console.log(event.detail)
    this.setData({
      show: false,
      date: this.formatDate(event.detail),
    });
  },
  //无合同原因
  noContractReasonChange(e) {
    // console.log(e.detail, '无合同原因')
    this.setData({
      noContractReason: e.detail,
    });
    //  this.save()
  },
  noContractReasonblur() {
    if (this.data.radio2 == 0 && this.data.noContractReason == '') {
      wx.showToast({
        title: '请输入无合同原因',
        icon: 'none'
      })
    }
    if (!this.data.sysDictCustomer) {
      this.data.sysDictCustomer = []
    }
    api.invEdit({
      method: 'post',
      data: {
        id: this.data.invid,
        updateBy: this.data.unitId,
        fpType: this.data.dictKey,
        taxRate: this.data.keyId,
        // money: this.data.moneyValue.toString().replace(/(?!^)(?=(\d{3})+\.)/g, ","),
        money: this.data.moneyValue.toString(),
        cusId: this.data.cusId,
        isReceived: this.data.radio,
        //到款项id
        receiveId: this.data.receiveId,
        dkClaimId: this.data.dkClaimId,
        receiveDate: this.data.getTime,
        sysDictCustomer: this.data.sysDictCustomer,
        needContract: parseInt(this.data.radio2),
        businessType: this.data.businessType,
        remarks: this.data.remarks,
        noContractReason: this.data.noContractReason //无合同原因
      },
      success: function (res) {
        // console.log(res.data.data, "invEdit")
        if (res.data.code == 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          })
        } else {
          // console.log('保存成功，但是不需要弹窗')
        }
      }
    })
  },
  //备注
  onremarksChange(e) {
    this.setData({
      remarks: e.detail,
    });
  },
  //点击取消 返回到上一页
  cancel() {
    wx.switchTab({
      url: '/pages/invoice/list/list',
    })
  },
  //点击下一步 提交新建发票内容
  clicknext() {
    if (this.data.businessTypeStr == '') {
      wx.showToast({
        title: '请先选择业务类型',
        icon: 'none'
      })
    } else if (this.data.typeValue == '') {
      wx.showToast({
        title: '请先选择发票类型',
        icon: 'none'
      })
    } else if (this.data.moneyValue == '') {
      wx.showToast({
        title: '请输入开票金额',
        icon: 'none'
      })
    } else if (this.data.taxesValue == '') {
      wx.showToast({
        title: '请正确填写开票金额（数字）',
        icon: 'none'
      })
    } else if (this.data.radio == '') {
      wx.showToast({
        title: '请选择是否到款',
        icon: 'none'
      })
    } else if (this.data.date == '') {
      wx.showToast({
        title: '请选择预计到款日期',
        icon: 'none'
      })
    } else if (this.data.radio2 == 0 && this.data.noContractReason == '') {
      wx.showToast({
        title: '请输入无合同原因',
        icon: 'none'
      })
    } else {
      // console.log(this.data.isOfflineYearClaimed)
      // console.log(this.data.dictKey2, "iiii")
      let that = this
      api.submitInv({
        method: 'post',
        data: {
          coId: this.data.coId,
          createBy: this.data.unitId,
          operatorId: this.data.unitId,
          opDeptId: this.data.deptId,
          businessType: this.data.businessType, //业务类型
          fpType: this.data.dictKey,
          taxRate: this.data.keyId,
          money: this.data.moneyValue,
          isReceived: this.data.radio,
          is_cpyjf: this.data.is_cpyjf,
          //到款项id
          receiveId: this.data.receiveId,
          dkClaimId: this.data.dkClaimId,
          receiveType: this.data.dictKey2, //到款类型
          receiveDate: this.data.getTime,
          remarks: this.data.remarks,
          needContract: parseInt(this.data.radio2),
          noContractReason: this.data.noContractReason, //无合同原因
          isOfflineClaimed: parseInt(this.data.isOfflineYearClaimed), // 线下或往年已认领 是否

        },
        success: function (res) {
          // console.log(res.data.data, "submitInv 点击下一步创建发票")
          if (res.data.code == 200) {
            that.setData({
              code: res.data.data.code,
              invid: res.data.data.id,
              uuid: res.data.data.uuid,
              invtaxRate: res.data.data.taxRateStr,
            })
            // console.log(that.data.invid, "创建发票id")
          }

        }
      })
      //提交之后开启下一步
      that.setData({
        clicknext: true
      })
    }
  },

  // //导入开票内容
  afterRead(event) {
    let that = this
    // console.log(event.detail, '导入开票内容')
    const {
      file
    } = event.detail;
    // console.log(file[0].url)
    wx.uploadFile({
      method: 'POST',
      url: 'https://api.gm.gmread.cn/payment_api/inv/content/excelImport',
      filePath: file[0].url,
      name: 'file',
      formData: {
        coId: that.data.coId,
        userId: that.data.unitId,
        invId: that.data.invid,
        taxRate: that.data.keyId,
      },
      header: {
        'Content-Type': 'multipart/form-data',
        'Authorization': wx.getStorageSync('userToken') ? wx.getStorageSync('userToken') : ''
      },
      success(res) {
        // console.log(res, '导入')
        let resData = JSON.parse(res.data)
        if (resData.code == 200) {
          that.getDate()
          that.sumMoneyByInvId()
          wx.showToast({
            title: resData.data,
          })
        } else {
          wx.showToast({
            title: resData.data,
          })
        }
      },
      fail(res) {
        // console.log(res, '失败')
      }
    });
  },

  //开票内容总金额
  sumMoneyByInvId() {
    let that = this;
    api.sumMoneyByInvId({
      data: {
        invId: that.data.invid,
      },
      success: function (res) {
        // console.log(res.data.data, "开票内容总金额")
        if (res.data.code == 200) {
          that.setData({
            total: res.data.data
          })
        }
      }
    })
  },



  //点击开票内容+
  addkaipiao() {
    wx.navigateTo({
      url: '/pages/newtask/newtask?id= ' + this.data.invid + '&code=' + this.data.code + '&keyId=' + this.data.keyId + '&userName=' + this.data.userName + '&deptName=' + this.data.deptName,
    })
  },
  //点击合同+
  addhetong() {
    wx.navigateTo({
      url: '/pages/newbill/newbill?id= ' + this.data.invid + '&unitId=' + this.data.unitId + '&cusId=' + this.data.cusId,
    })
  },
  //点击任务号+
  addrenwuhao() {
    wx.navigateTo({
      url: '/pages/addrenwuhao/addrenwuhao?id= ' + this.data.invid + '&unitId=' + this.data.unitId + '&cusId=' + this.data.cusId + '&invtaxRate=' + this.data.invtaxRate,
    })
  },
  //点击往来单位+
  addwanglaidw() {
    // from=1 从新建发票页面点击
    wx.navigateTo({
      url: '/pages/intercourseUnit/intercourseUnit?from= ' + 1 + '&invid=' + this.data.invid,
    })
  },
  //点击  跳转到开票内容详情
  clickItem(e) {
    wx.navigateTo({
      url: '/pages/invContdetails/invContdetails?id= ' + e.currentTarget.dataset.id + '&saveButton=' + this.data.saveButton,
    })
  },
  //点击  跳转到合同详情
  clickItemcon(e) {
    // console.log(e.currentTarget.dataset.id, '!!!')
    wx.navigateTo({
      url: '/pages/taskNumdetails/taskNumdetails?id= ' + e.currentTarget.dataset.id + '&saveButton=' + this.data.saveButton,
    })
  },
  //点击  跳转到任务号详情
  clickrenwuhao(e) {
    // console.log(e.currentTarget.dataset.id, '!!!')
    wx.navigateTo({
      url: '/pages/taskNumdetails/taskNumdetails?id= ' + e.currentTarget.dataset.id + '&saveButton=' + this.data.saveButton,
    })
  },
  //税号 
  onitinChange(event) {
    this.setData(
      this.data.sysDictCustomer[0].itin = event.detail
    )
  },
  //地址 
  onaddressChange(event) {
    this.setData(
      this.data.sysDictCustomer[0].address = event.detail
    )
  },
  //开户行 
  onopeningBankChange(event) {
    this.setData(
      this.data.sysDictCustomer[0].openingBank = event.detail
    )
  },
  //银行卡号 
  onbankAccountChange(event) {
    if ((event.detail.length) % 5 == 0) {
      event.detail = event.detail + ''
    }
    this.setData(
      this.data.sysDictCustomer[0].bankAccount = event.detail
    )
  },
  //点击保存
  save() {
    if (this.data.radio2 == 0 && this.data.noContractReason == '') {
      wx.showToast({
        title: '请输入无合同原因',
        icon: 'none'
      })
    }
    this.setData({
      sysDictCustomer: this.data.sysDictCustomer
    })
    // console.log(this.data.sysDictCustomer)
    if (!this.data.sysDictCustomer) {
      this.data.sysDictCustomer = []
      // wx.showToast({
      //   title: '请先添加合同',
      //   icon: 'none'
      // })
    }
    let that = this;
    api.invEdit({
      method: 'post',
      data: {
        id: this.data.invid,
        updateBy: this.data.unitId,
        fpType: this.data.dictKey,
        taxRate: this.data.keyId,
        // money: this.data.moneyValue.toString().replace(/(?!^)(?=(\d{3})+\.)/g, ","),
        money: this.data.moneyValue.toString(),
        cusId: this.data.cusId,
        isReceived: this.data.radio,
        receiveType: this.data.dictKey2, //到款类型
        //到款项id
        receiveId: this.data.receiveId,
        dkClaimId: this.data.dkClaimId,
        receiveDate: this.data.getTime,
        sysDictCustomer: this.data.sysDictCustomer,
        needContract: parseInt(this.data.radio2),
        businessType: this.data.businessType,
        remarks: this.data.remarks,
        noContractReason: this.data.noContractReason //无合同原因
      },
      success: function (res) {
        // console.log(res.data.data, "invEdit")
        if (res.data.code == 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          })
        } else {
          wx.showModal({
            content: res.data.message,
            showCancel: false,
            confirmColor: '#0041C4'
          })
        }
      }
    })

  },

  //点击提交
  sub() {
    if (this.data.radio2 == 0 && this.data.noContractReason == '') {
      wx.showToast({
        title: '请输入无合同原因',
        icon: 'none'
      })
    }
    this.setData({
      sysDictCustomer: this.data.sysDictCustomer
    })
    // console.log(this.data.sysDictCustomer)
    if (!this.data.sysDictCustomer) {
      this.data.sysDictCustomer = []
      // wx.showToast({
      //   title: '请先添加合同',
      //   icon: 'none'
      // })
    }
    let that = this;
    api.invEdit({
      method: 'post',
      data: {
        id: this.data.invid,
        updateBy: this.data.unitId,
        fpType: this.data.dictKey,
        taxRate: this.data.keyId,
        // money: this.data.moneyValue.toString().replace(/(?!^)(?=(\d{3})+\.)/g, ","),
        money: this.data.moneyValue.toString(),
        cusId: this.data.cusId,
        isReceived: this.data.radio,
        //到款项id
        receiveId: this.data.receiveId,
        dkClaimId: this.data.dkClaimId,
        receiveDate: this.data.getTime,
        sysDictCustomer: this.data.sysDictCustomer,
        needContract: parseInt(this.data.radio2),
        businessType: this.data.businessType,
        remarks: this.data.remarks,
        noContractReason: this.data.noContractReason //无合同原因

      },
      success: function (res) {
        // console.log(res.data.data, "invEdit")
        if (res.data.code == 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          })
          // let that = this;
          api.invSubmit({
            method: 'POST',
            data: {
              coId: that.data.coId,
              uuid: that.data.uuid,
              invId: that.data.invid,
              deptId: that.data.deptId,
              userId: that.data.unitId,
            },
            success: function (res) {
              console.log(res.data.data, "invSubmit")
              if (res.data.code == 200) {
                wx.showModal({
                  content: '发票提交成功',
                  showCancel: false,
                  confirmColor: '#0041C4',
                  success: function (res) {
                    if (res.confirm) {
                      setTimeout(() => {
                        wx.navigateBack({
                          delta: 1,
                        })
                      }, 100);
                    }
                  }
                })
              } else {
                wx.showModal({
                  content: res.data.message,
                  showCancel: false,
                  confirmColor: '#0041C4'
                })
              }
            }
          })
        } else {
          wx.showModal({
            content: res.data.message,
            showCancel: false,
            confirmColor: '#0041C4'
          })
        }
      }
    })

    // wx.removeStorageSync('receTerm2');
    // wx.removeStorageSync('receTerm');
    // wx.removeStorageSync('dkClaimId');
    // wx.removeStorageSync('receiveId');
  },
  //删除开票内容list
  delkaipiao(e) {
    let index = e.currentTarget.dataset.index;
    let that = this
    Dialog.confirm({
        message: '确定删除吗？',
      })
      .then(() => {
        api.delkaipiao({
          data: {
            id: e.currentTarget.dataset.id
          },
          success: function (res) {
            if (res.data.code == 200) {
              that.sumMoneyByInvId()
              that.data.invFormContentList.splice(index, 1)
              that.setData({
                invFormContentList: that.data.invFormContentList
              })
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
            }
          }
        })
      })
      .catch(() => {
        // on cancel
        console.log('取消操作')
      });
  },
  //删除合同list
  delhetong(e) {
    console.log(e, "789")
    let index = e.currentTarget.dataset.index;
    let that = this
    Dialog.confirm({
        message: '确定删除吗？',
      })
      .then(() => {
        api.delhetong({
          data: {
            id: e.currentTarget.dataset.id,
            invId: that.data.invid
          },
          success: function (res) {
            if (res.data.code == 200) {
              that.data.sysDictContractList.splice(index, 1)
              that.setData({
                sysDictContractList: that.data.sysDictContractList
              })
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
            }
          }
        })
      })
      .catch(() => {
        // on cancel
        // console.log('取消操作789')
      });
  },

  //删除合同任务号分摊list
  delfentan(e) {
    let index = e.currentTarget.dataset.index;
    let that = this
    Dialog.confirm({
        message: '确定删除吗？',
      })
      .then(() => {
        api.delfentan({
          data: {
            id: e.currentTarget.dataset.id
          },
          success: function (res) {
            if (res.data.code == 200) {
              // console.log('yyds')
              that.data.sysDictContractList.forEach((item) => {
                // console.log(item, "iten")
                item.invFormTaskList.splice(index, 1)
                that.setData({
                  invFormTaskList: item.invFormTaskList
                })
              })
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
            }
          }
        })
      })
      .catch(() => {
        // on cancel
        // console.log('取消操作')
      });
  },

  //删除任务号list
  delrenwuhao(e) {
    let index = e.currentTarget.dataset.index;
    let that = this
    Dialog.confirm({
        message: '确定删除吗？',
      })
      .then(() => {
        api.delrenwuhao({
          data: {
            id: e.currentTarget.dataset.id,
          },
          success: function (res) {
            if (res.data.code == 200) {
              // console.log('yyds')
              that.data.invTaskList.splice(index, 1)
              that.setData({
                invTaskList: that.data.invTaskList
              })
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
            }
          }
        })
      })
      .catch(() => {
        // on cancel
        // console.log('取消操作')
      });
  },

  //银行卡格式
  backcard(e) {
    // console.log(e)
    if (this.data.bankAccount) {
      if ((this.data.bankAccount.length + 1) % 5 == 0) {
        bankAccount = bankAccount + ''
      }
      this.setData({
        bankAccount: bankAccount
      })
    }
  },
  addComma(date) {
    let str = '';
    let num = '';
    let newStr = '';
    date = date + '';
    if (date.indexOf('.') != -1) {
      num = date.split('.')[0]
      str = date.split('.')[1]
    } else {
      num = date
    }
    newStr = num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
    newStr = str == '' ? newStr : newStr + '.' + str;
    return newStr;
  },
  getDate() {
    if (this.data.invid) {
      let that = this
      api.newget({
        data: {
          id: this.data.invid
        },
        success: function (res) {
          // console.log(res.data.data, "newget")
          if (res.data.code == 200) {
            //开票内容
            if (res.data.data.invFormContentList.length > 0) {
              for (let i = 0; i < res.data.data.invFormContentList.length; i++) {
                res.data.data.invFormContentList[i].money = that.addComma(res.data.data.invFormContentList[i].money)
              }
            }
            //合同
            if (res.data.data.sysDictContractList.length > 0) {
              for (let i = 0; i < res.data.data.sysDictContractList.length; i++) {
                res.data.data.sysDictContractList[i].waitMoney = that.addComma(res.data.data.sysDictContractList[i].waitMoney)
                res.data.data.sysDictContractList[i].money = that.addComma(res.data.data.sysDictContractList[i].money)
                if (res.data.data.sysDictContractList[i].invFormTaskList.length > 0) {
                  // console.log(3333)
                  let invFormTaskList = res.data.data.sysDictContractList[i];
                  // console.log(invFormTaskList)
                  for (let items = 0; items < invFormTaskList.length; items++) {
                    // console.log(invFormTaskList[items])
                    res.data.data.invFormTaskList[i].contTaskMoney = that.addComma(res.data.data.invFormTaskList[i].contTaskMoney)
                    res.data.data.invFormTaskList[i].money = that.addComma(res.data.data.invFormTaskList[i].money)
                  }
                }
              }
              //任务号
              if (res.data.data.invTaskList.length > 0) {
                for (let i = 0; i < res.data.data.invTaskList.length; i++) {
                  res.data.data.invTaskList[i].money = that.addComma(res.data.data.invTaskList[i].money)
                }
              }
              //往来单位
              if (res.data.data.sysDictCustomer.length > 0) {
                for (let i = 0; i < res.data.data.sysDictCustomer.length; i++) {
                  //   res.data.data.sysDictCustomer[i].bankAccount = res.data.data.sysDictCustomer[i].bankAccount.toString().replace(/\s/g, '').replace(/(.{4})/g, "$1 ")
                }
              }
            }
            that.setData({
              money: res.data.data.money,
              cusId: res.data.data.cusId,
              saveButton: res.data.data.saveButton,
              invFormContentList: res.data.data.invFormContentList,
              sysDictContractList: res.data.data.sysDictContractList,
              sysDictCustomer: res.data.data.sysDictCustomer,
              invTaskList: res.data.data.invTaskList,
              radio2: res.data.data.needContract.toString(), //是否关联合同
              noContractReason: res.data.data.noContractReason, //无合同原因
              // cusId:res.date.data.cusId
            })
            // console.log(that.data.saveButton, "savebutton")
          }
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log()
    this.setData({
      wlid: options.wlid,
      wlname: options.wlname,
      date: `${new Date().getFullYear()-1}/12/31`
    })
    // console.log(this.data.wlname,'往来xx')
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    this.data.coId = wx.getStorageSync('userInfo').coId
    this.data.unitId = wx.getStorageSync('userInfo').unitId

    // this.sumMoneyByInvId()

    //选择到款项 带出的 到款日期、到款类型
    this.data.dictKey2 = wx.getStorageSync('bankType');
    this.data.date = wx.getStorageSync('date');

    this.setData({
      receiveType: wx.getStorageSync('bankTypeStr'),
      dictKey2: wx.getStorageSync('bankType'),
      // date: wx.getStorageSync('date') ? this.formatDate(new Date(wx.getStorageSync('date'))) : '',
      receTermCode: wx.getStorageSync('receTermCode') ? wx.getStorageSync('receTermCode') : '',
      date: wx.getStorageSync('receTermDate') ? wx.getStorageSync('receTermDate') : that.formatDate(new Date())
    })
    // if (wx.getStorageSync('receTerm')) {
    //   this.setData({ //到款项（未）
    //     receTermCode: wx.getStorageSync('receTerm'),
    //   });
    //   console.log(this.data.receTermCode, '未到款的')
    // } else if (wx.getStorageSync('receTerm2')) {
    //   this.setData({ //到款项 （已）
    //     receTermCode: wx.getStorageSync('receTerm2')
    //   });
    //   console.log(this.data.receTermCode, '已到款的')
    // }

    //获取到的到款项id
    if (wx.getStorageSync('receiveId')) {
      this.data.receiveId = wx.getStorageSync('receiveId') ? wx.getStorageSync('receiveId') : '';
      //  console.log(this.data.receiveId,'（未认领)receiveId')
    } else if (wx.getStorageSync('dkClaimId')) {
      this.data.dkClaimId = wx.getStorageSync('dkClaimId') ? wx.getStorageSync('dkClaimId') : '';
      // console.log(this.data.dkClaimId,'(已认领)dkClaimId')
    }



    //获取用户部门
    api.invNumber({
      data: {
        userId: this.data.unitId,
      },
      success: function (res) {
        if (res.data.code = 200) {
          that.setData({
            userName: res.data.data.userName,
            deptName: res.data.data.deptName,
            deptId: res.data.data.deptId
          })
        }
      }
    })
    // 页面的回显
    that.getDate()



  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})